export function drawImage(ctx, img, { x, y, w, h, r }, isFill = false) {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: img,
      success: async (res) => {
        await ctx.save();
        await ctx.beginPath();
        await this.drawRoundRect(ctx, x, y, w, h, r);
        await ctx.clip();
        isFill && ctx.fill();
        await ctx.drawImage(res.path, x, y, w, h);
        await ctx.restore();
        resolve();
      },
      fail: (res) => {
        resolve();
      }
    });
  }).catch(() => {
    console.error("画图片失败");
  });
}

export function drawText(ctx, str, x, y, lineHeight, lineWidth, limitHeight) {
  const totalWidth = ctx.measureText(str).width;
  lineHeight = lineHeight || parseInt(ctx.font) || 24;
  y += lineHeight; // fillText时，y是左下角，所以加上行高，得到左上角，符合习惯
  const baseY = y;
  // 长度不超出 、未设置宽度，直接写一行
  if (!lineWidth || (lineWidth && totalWidth <= lineWidth)) {
    ctx.fillText(str, x, y);
    return lineHeight;
  }
  let lines = -1;
  let lineCount = 1;
  let baseIndex = 0;
  limitHeight && (lines = Math.floor(limitHeight / lineHeight) || 1); // 总行数 向下取整
  for (let i = 0; i < str.length; i++) {
    let subStr = str.substring(baseIndex, i); // 剪出一段长度并判断是否需要换行
    const w = ctx.measureText(subStr).width;
    if (w >= lineWidth || i === str.length - 1) {
      baseIndex = i; // 换行
      lineCount++;
      // 超出设置行数
      if (limitHeight && lineCount > lines && i !== str.length - 1) {
        subStr = `${subStr.substring(0, subStr.length - 2)}...`;
        ctx.fillText(subStr, x, y);
        y += lineHeight;
        break;
      }
      ctx.fillText(subStr, x, y);
      y += lineHeight + (i === str.length - 1 ? 0 : 10); // 10是行间距
    }
  }
  return y - baseY;
}

export function drawRoundRect(ctx, originX, originY, width, height, radius) {
  // 左上角
  ctx.arc(originX + radius, originY + radius, radius, Math.PI, (Math.PI * 3) / 2, false);
  ctx.lineTo(originX + width - radius, originY);
  // 右上角
  ctx.arc(originX + width - radius, originY + radius, radius, (Math.PI * 3) / 2, Math.PI * 2, false);
  ctx.lineTo(originX + width, originY + height - radius);
  // 右下角
  ctx.arc(originX + width - radius, originY + height - radius, radius, 0, Math.PI / 2, false);
  ctx.lineTo(originX + width - radius, originY + height);
  // 左下角
  ctx.arc(originX + radius, originY + height - radius, radius, Math.PI / 2, Math.PI, false);
  ctx.lineTo(originX, originY + radius);
}

export function canvasToTempFilePath(ctx, canvasId, that) {
  return new Promise((resolve, reject) => {
    let img = "";
    ctx.draw(true, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath(
          {
            canvasId,
            success: (res) => {
              img = res.tempFilePath; // 在H5平台下，tempFilePath 为 base64
            },
            fail: (error) => {
              console.log(`error`, error);
              uni.showToast({
                title: "图片加载失败",
                duration: 2000
              });
            },
            complete: (res) => {
              resolve(img);
              uni.hideLoading();
            }
          },
          that
        );
      }, 300);
    });
  });
}

export function saveImage(imgUrl) {
  uni.showActionSheet({
    itemList: ["保存图片", "取消"],
    success: (res) => {
      if (res.tapIndex == 0) {
        uni.saveImageToPhotosAlbum({
          filePath: imgUrl, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
          success: () => {
            uni.showToast({
              title: "保存成功",
              duration: 2000
            });
          },
          fail: (e) => {
            console.error(e, "----");
            uni.showToast({
              title: "保存失败",
              duration: 2000
            });
          }
        });
      }
    },
    fail(res) {
      console.log(res.errMsg);
    }
  });
}
